package com.gitee.cui.client.handler;

import com.gitee.cui.client.client.ClientSession;
import com.gitee.cui.client.client.CommandController;
import com.gitee.cui.common.common.exception.InvalidFrameException;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 异常处理器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/27 17:17
 **/
@Slf4j
@ChannelHandler.Sharable
@Service
public class ExceptionHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private CommandController commandController;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
        if (cause instanceof InvalidFrameException) {
            ClientSession.getSession(ctx).close();
        } else {
            ctx.close();

            // 开始重连
            commandController.setConnectFlag(false);
            commandController.startConnectServer();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
